package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.enums.NoticeLevelEnum;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.util.JsonResult;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IEmployeeService employeeService;

    /*@RequiredPermission(name="公告列表",expression="notice:list")*/
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") NoticeQueryObject qo){
        //当前用户id
        Long employeeId = UserContext.getCurrentUser().getId();

        PageInfo<Notice> pageInfo = noticeService.query(qo,employeeId);
        //页面显示数
        model.addAttribute("pageInfo", pageInfo);
        //当前用户数据，判断能拥有哪些按钮
        model.addAttribute("employee",UserContext.getCurrentUser());
        //公告等级
        model.addAttribute("noticeLevels",NoticeLevelEnum.values());

        return "notice/list";
    }


    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name="公告新增/编辑",expression="notice:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Notice notice){
        if (notice.getId() != null) {
            noticeService.update(notice);
        }else {
            //新增时需要同时将关联表的数据加入到数据库中
            //对每一个新增的公告分配给每一个数据库中的用户
            //查询所有的用户,里面每一个都有id
            List<Employee> employees = employeeService.list();
            noticeService.save(notice,employees);
        }
        return new JsonResult();
    }



    //修改发布状态
    @RequestMapping("/updateNoticeStatus")
    @ResponseBody
    public JsonResult updateNoticeStatus(Long id,Boolean status){
        noticeService.updateNoticeStatus(id,status);
        return new JsonResult();
    }

    //跳转到详情页面所需要进行的操作
    @RequestMapping("/show")
    @ResponseBody
    public JsonResult show(Long id){
        //消息状态：未读/已读
        noticeService.updateMsgStatus(id,UserContext.getCurrentUser().getId());

        return new JsonResult();
    }
    //展示信息详情页面
    @RequestMapping("/showInfo")
    public String showInfo(Model model,Long id){
        Notice notice = noticeService.get(id);
        model.addAttribute("notice",notice);
        return "/notice/show";
    }
}
